﻿using System;
using System.Collections.Generic;
using System.Configuration;
using System.IO;
using System.Text;
using System.Threading;

namespace DirectoryWatcherServices
{
    public class Service
    {
        #region Attributes

        public struct Path
        {
            public string Directory;
            public string ReposPath;
            public string CodePath;
        }

        public static Path StructPath;
        
        protected static string logpath = ConfigurationManager.AppSettings["LOGPATH"].ToString();

        #endregion

        public Service()
        {
        }

        public Service(Path path)
        {
            StructPath = path;
        }

        public void Start()
        {
            WatcherThread();
            FileStream fs = new FileStream(logpath, FileMode.Append, FileAccess.Write, FileShare.ReadWrite);
            StreamWriter txt = new StreamWriter(fs);
            txt.WriteLine(DateTime.Now.ToLongTimeString() + " " + StructPath.Directory);
            txt.Close();
        }

        protected void WatcherThread()
        {
            FileStream fs = new FileStream(logpath, FileMode.Append, FileAccess.Write, FileShare.ReadWrite);
            StreamWriter txt = new StreamWriter(fs);
            txt.WriteLine(DateTime.Now.ToLongTimeString() + " " + StructPath.Directory + " Watcher");
            txt.Close();

            FileSystemWatcher Watcher = new FileSystemWatcher();
            Watcher.Path = StructPath.Directory;
            Watcher.NotifyFilter = NotifyFilters.Attributes | NotifyFilters.DirectoryName | NotifyFilters.FileName | NotifyFilters.LastWrite | NotifyFilters.Size;


            FileStream fs1 = new FileStream(logpath, FileMode.Append, FileAccess.Write, FileShare.ReadWrite);
            StreamWriter txt1 = new StreamWriter(fs1);
            txt1.WriteLine(DateTime.Now.ToLongTimeString() + " " + StructPath.Directory + " " + Watcher.Path);
            txt1.Close();

            Watcher.Changed += new FileSystemEventHandler(OnChanged);
            Watcher.Created += new FileSystemEventHandler(OnChanged);
            Watcher.Deleted += new FileSystemEventHandler(OnChanged);
            Watcher.Renamed += new RenamedEventHandler(OnChanged);

            Watcher.EnableRaisingEvents = true;
        }

        protected void OnChanged(object source, FileSystemEventArgs e)
        {
            FileStream fs = new FileStream(logpath, FileMode.Append, FileAccess.Write, FileShare.ReadWrite);
            StreamWriter txt = new StreamWriter(fs);
            txt.WriteLine(DateTime.Now.ToLongTimeString() + " " + StructPath.Directory + e.ChangeType + e.FullPath);
            txt.Close();
        }
    }
}
